package com.biscuit.page.basicservice.conf.handler;

import com.biscuit.common.base.BaseResponse;
import com.biscuit.common.base.BaseResponseVoid;
import com.biscuit.page.basicservice.model.enums.BaseResponseEnum;
import com.biscuit.page.basicservice.model.exception.BaseException;
import com.biscuit.page.basicservice.utils.BaseResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author mazihao
 * @createTime 2024/3/8 11:08
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public BaseResponse<BaseResponseVoid> exceptionHandler(Exception e) {
        BaseResponse<BaseResponseVoid> result = BaseResponseUtil.fail(BaseResponseEnum.ERROR_SERVICE);
        String errorMessage = null;
        if (e instanceof NullPointerException) {
            errorMessage = "系统内部异常（NullPointerException）";
        } else if (e instanceof RuntimeException) {
            errorMessage = "系统内部异常（RuntimeException）";
        } else {
            errorMessage = e.getMessage();
        }
        result.setMessage(errorMessage);
        return result;
    }

    @ExceptionHandler(value = BaseException.class)
    public BaseResponse<BaseResponseVoid> baseExceptionHandler(BaseException e) {
        BaseResponse<BaseResponseVoid> result = BaseResponseUtil.fail(BaseResponseEnum.ERROR_PARAM);
        if (StringUtils.isNotBlank(e.getMessage())) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

}
